﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using WpfUMLTry1;

namespace WpfUMLTry1.Model
{
    public class gameModel
    {
        #region private fields
        private PlayerCharacter _theHero;   //The character of the user
        private Monster _enemyCreature;     //Enemy Mob, if there is a fight, otherway - zero
        private Timer tmr;                  //Timer for fighting
        private Int32 _storyState;          //Save of story state   // 0 - start
        private List<Quest.AbstractQuest> qList;    //Quests
        private Boolean first;             //First time in "Quest" option [follow signs] - every page change to "InTheTown" start this autmatically
        private Int32 _numberOfSaveSlot;    //Important for file/data handling
        #endregion
        
        public PlayerCharacter GetPlayCaharacter()
        {
            return _theHero;
        }
        public void addCharacterToTheGame(PlayerCharacter theHero)
        {
            _theHero = theHero;
        }
        public Int32 storyState 
        {
            get { return _storyState; } 
            set 
            { 
                _storyState = value; 
                Data.GameDataManager.SaveGame(this);    //when State changed -> game save
            } 
        }
        public Int32 numberOfSaveSlot
        {
            get { return _numberOfSaveSlot; }
            set
            {
                if (value > 0 && value <= 3)
                    _numberOfSaveSlot = value;
                else
                    _numberOfSaveSlot = 0;  // safety if slot number is wrong
            }
        }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="saveSlot">Number of the using game slot</param>
        /// <param name="state">Quest State</param>
        public gameModel(Int32 saveSlot, Int32 state = 0)
        {
            numberOfSaveSlot = saveSlot;
            InitQuests();
            first = true;
            _storyState = state;
        }

        //Main Functions
        public String RestInTheInn()
        {
            _theHero.HP = _theHero.maxHP;
            _theHero.RestInTheInn();
            return "You slept well. Now you are fully restored\n";
        }
        public void GoToTheForest() //Random mob fight
        {
            _enemyCreature = RandomNewMonster(_theHero.level);
            View.Switcher.Switch(new View.Fight_page(),new ViewModel.Fight_VM(this, _enemyCreature));
            FightingStanceStart();
        }
        public void followTheSigns()    //do the quest
        {
            if (storyState == 0)
                qList[0].startQuest(0);
            else if (storyState == 1)
                qList[1].startQuest(1);
            else if (storyState == 2)
            {
                _enemyCreature = new Monster("Wolf") { bAgi = 5, bStr = 5, bVit = 5, experience = 10, level = 1 };
                storyState = 3;
                FightingStanceStart();
                View.Switcher.Switch(new View.Fight_page(), new ViewModel.Fight_VM(this, _enemyCreature));
            }
            else if (storyState == 3)
                qList[2].startQuest(3);
            else if (storyState == 4 && !first)
            {

            }
            if (first)
                first = false;
            
        }

        #region Privet functions
        #region Fighting
        private void FightingStanceStart()  //Init
        {
            _theHero.StepInToNewFight();
            _enemyCreature.CreatureDead += new EventHandler(EnemyDead);
            _enemyCreature.ReadyToAttack += new EventHandler(EnemyReadyToAttack);
            _theHero.ReadyToAttack += new EventHandler(OnPlayerReadyToAttack);
            tmr = new Timer(50);
            tmr.Elapsed += new ElapsedEventHandler(FightingTimerElapsed);
            tmr.Start();

        }

        private void FightingTimerElapsed(object sender, ElapsedEventArgs e)
        {
            _enemyCreature.fightingTimerElapsed();
            _theHero.fightingTimerElapsed();
            OnFightingTimerTick();  //For VM refresh
        }

        private void EnemyDead(object sender, EventArgs e)
        {
            tmr.Stop();
            _enemyCreature = null;
            Data.GameDataManager.SaveGame(this);
        }

        private void EnemyReadyToAttack(object sender, EventArgs e)
        {
            tmr.Stop(); //Stop till attack
            _enemyCreature.BasicAttack(_theHero);
            tmr.Start();    //Attack done -> Timer start
        }

        public void PlayerAttackDone_Cont()
        {
            if (_enemyCreature != null)
                tmr.Start();    //player did his move, timer start (if there is enemy)
        }

        public event EventHandler PlayerReadyToAttack;

        //PlayereadyToAttack caller
        private void OnPlayerReadyToAttack(object sender, EventArgs e)
        {
            tmr.Stop(); //stop till palyer attack
            if(PlayerReadyToAttack != null)
                PlayerReadyToAttack(this, new EventArgs() );
        }

        private void OnFightingTimerTick()
        {
            if(FightingTimerTick != null)
                FightingTimerTick(this, new EventArgs() );
        }
        #endregion
        private Monster RandomNewMonster(Int32 levelInfo)
        {
            Monster mob = new Monster("Wolf");
            List<Int32> stats = new List<int>();
            for (int i = 0; i < 5; ++i)
                stats.Add(5);
            mob.SetAllStat(stats);
            return mob;
        }
        #region Quests
        private void InitQuests()
        {
            qList = new List<Quest.AbstractQuest>();
            Quest.QuestChooseTxt QCHT;
            #region Quests inits #0 : 0 - The begining
            QCHT = new Quest.QuestChooseTxt(0, this)
            {
                state = 0,
                textOfQuest = "You just woke from your sweet dream.\nA wolf is staying few steps from you with blood red eyes, and snarling.\n" +
                                "You have your weapon with you, but you know,\nthe town is near, maybe you can reach it.\nThe wolf won't follow you in the town."
            };
            QCHT.addNewAnswer("Run to the town", 1);
            QCHT.addNewAnswer("Fight!", 2);
            //QCHT.answerChosed += new EventHandler<int>(questAnswered);

            qList.Add(QCHT);
            #endregion
            #region Quest #1 : 1 - you cant run away
            QCHT = new Quest.QuestChooseTxt(1, this)
            {
                state = 1,
                textOfQuest = "The wolf is unordinary fast. You can't reach the town"
            };
            QCHT.addNewAnswer("Fight for your life", 2);
            qList.Add(QCHT);
            #endregion
            #region Quest #2 : 3 - You won, back to the town
            QCHT = new Quest.QuestChooseTxt(1, this)
            {
                state = 1,
                textOfQuest = "You beat the beast!\nAfter the combat you saw some kind of sign on the wolf\nSome days ago you saw something similar ind the forest.\nBut now you have to get some rest."
            };
            QCHT.addNewAnswer("Go back to the town", 4);
            qList.Add(QCHT);
            #endregion

        }
        #endregion
        #endregion



        #region events
        public event EventHandler FightingTimerTick;
        #endregion
    }
}
